package org.example.common.codec;

import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.CorruptedFrameException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 解码器
 * @time 2025/6/17 0:21
 */
@Slf4j
@Component
public class InvocationDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 标记当前读取位置
        in.markReaderIndex();
        // 判断是否能够读取 length 长度
        if (in.readableBytes() <= 4) {
            return;
        }
        // 读取 length
        int length = in.readInt();
        if (length < 0) {
            throw new CorruptedFrameException("数据长度不能小于 0" + length);
        }
        // 如果message 的长度不足，则退回原读取位置
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            return;
        }
        // 读取内容
        byte[] bytes = new byte[length];
        in.readBytes(bytes);
        // 解析成 Invocation
        String jsonStr = new String(bytes, StandardCharsets.UTF_8);
        log.info("[decode][连接({})] 读取的 JSON 字符串: {}", ctx.channel().id(), jsonStr);

        try {
            Invocation invocation = JSONObject.parseObject(jsonStr, Invocation.class);
            out.add(invocation);
            log.info("[decode][连接({})] 解析出一条消息: {}", ctx.channel().id(), jsonStr);
        } catch (JSONException e) {
            log.error("[decode][连接({})] 消息:{} 解析失败: {}", ctx.channel().id(),jsonStr, e);
            // 处理异常
        }
    }
}
